#include "maindialog.h"
#include "ui_maindialog.h"

MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);

    sock = new QTcpSocket(this);

    connect(sock, SIGNAL(connected()), this, SLOT(connected()));
    connect(sock, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(sock, SIGNAL(readyRead()), this, SLOT(recvMsg()));
    connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(commError(QAbstractSocket::SocketError)));

    sock->connectToHost("124.71.188.13", 9999);

    ui->edtRecord->appendPlainText("\n正在连接服务器(124.71.188.13:9999)...\n");

    ui->edtMsg->setFocus();
}

MainDialog::~MainDialog()
{
    delete ui;
}

void MainDialog::connected()
{
    ui->edtRecord->appendPlainText("\n连接服务器成功！\n");
}

void MainDialog::disconnected()
{
    ui->edtRecord->appendPlainText("\n与服务器的连接已断开！\n");

//    sock->close();
//    sock->connectToHost("124.71.188.13", 9999);

    //    ui->edtRecord->appendPlainText("\n尝试重新连接服务器(124.71.188.13:9999)...\n");
}

void MainDialog::recvMsg()
{
    static QByteArray buff;

    buff += sock->readAll();

    int pos = buff.indexOf('\0');

    if(pos != -1)
    {
        QByteArray msg = buff.left(pos);
        ui->edtRecord->appendPlainText(QString("\n%1\n").arg(QString::fromUtf8(msg)));
        buff = buff.mid(pos + 1);
    }
}

void MainDialog::commError(QAbstractSocket::SocketError socketError)
{
    ui->edtRecord->appendPlainText("\n连接服务器失败！\n");

//    sock->close();
//    sock->connectToHost("124.71.188.13", 9999);

//    ui->edtRecord->appendPlainText("\n尝试重新连接服务器(124.71.188.13:9999)...\n");
}


void MainDialog::on_btnSend_clicked()
{
    QString msg = ui->edtMsg->toPlainText().trimmed();

    if(msg.isEmpty())
    {
        ui->edtMsg->clear();
        ui->edtMsg->setFocus();
        return;
    }

    QByteArray data = msg.toUtf8() + '\0';

    data = data.left(1025);

    if(sock->write(data) == data.size())
    {
        ui->edtRecord->appendPlainText(QString("\n%1\n").arg(msg));
        ui->edtMsg->clear();
        ui->edtMsg->setFocus();
    }
}
